<?php
/**
 * Created by Administrator
 * User: longli
 * Date: 2020/08/21
 * Time: 19:23
 * @link http://www.lmterp.cn
 */

namespace app\common\service\import;


use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\AccountPlatform;
use app\common\model\ProductPlatformSku;
use app\common\model\ProductStore;
use app\common\service\product\ProductService;

/**
 * 导入平台sku和内部sku生成映射关系
 * Class PlatformSku
 * @package app\common\service\import
 */
class PlatformSku extends BaseImport
{

    /**
     * 交换键值后读入头信息
     * @var array
     */
    protected $hsku = [];

    /**
     * 原读入头信息
     * @var array
     */
    protected $esku = [];

    protected $excludeField = ['sku.create_time'];

    public function init()
    {
        $this->esku = (new \app\common\service\export\PlatformSku())->getHeader();
        $this->hsku = array_flip($this->esku);
    }

    protected function write()
    {
        return ProductPlatformSku::limit(500)->insertAll($this->buildData()) > 0;
    }

    /**
     * 构建导入数据
     * @return array
     * @date 2020/09/16
     * @author longli
     */
    protected function buildData()
    {
        $ret = [];
        foreach($this->getData() as $item)
        {
            foreach($this->excludeField as $k) unset($item[$k]);
            $this->transform($item);
            $ret[] = ProductPlatformSku::getFilterField($item);
        }
        return $ret;
    }



    protected function validate(&$row = [], $key = 0)
    {
        $row = Tools::replaceArrayKey($this->hsku, $row);
        $error = [];
        if(!ProductStore::hasSku($row['sku.sku'])) $error[] = "sku【{$row['sku.sku']}】不存在";
        if(ProductPlatformSku::hasPlatformSku($row['sku.platform_sku'])) $error[] = "平台sku【{$row['sku.platform_sku']}】已存在";
        if(!Account::hasAccount($row['account.username'])) $error[] = "店铺账号【{$row['account.username']}】不存在";
        //if(!AccountPlatform::hasName($row['platform.name'])) $error[] = "平台【{$row['platform.name']}】不存在";
        if(!empty($error)) return join(", ", $error);
        return true;
    }

    protected function transform(& $row = [])
    {
        if(!empty($row['account.username'])) $row['sku.account_id'] = Account::getByName($row['account.username'])->account_id;
        if(!empty($row['sku.sku']))
        {
            $store = ProductStore::get(['sku' => $row['sku.sku']]);
            $row['sku.store_id'] = $store->store_id;
            $row['sku.product_id'] = $store->product_id;
        }
        $row = ProductService::getInstance()->parseRequestData($row)['sku'];
    }
}